﻿using System.Web.Mvc;
using MMSWebsite.DataAccessManagement;
using MMSWebsite.HtmlHepler;
using MMSWebsite.Models;

namespace MMSWebsite.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/
        AccountProvider _accountProvider = new AccountProvider();
        EmployeeAccessProvider _eap = new EmployeeAccessProvider();
        public static EmployeeViewModel EmpAccount;
        public ActionResult LogOn()
        {
            if(User.Identity.IsAuthenticated)
            {
                EmpAccount = _eap.GetEmployeeByCode(User.Identity.Name);
                //AuthenticateRedirection(EmpAccount);
                var roles = _eap.GetRolesOfEmp(EmpAccount);

                if (roles[0].Contains("FV")) return RedirectToAction("FVCustomers", "CusMgn");
                if (roles[0].Contains("Reviewer")) return RedirectToAction("Allocation", "CusMgn");
                if (roles[0].Contains("Admin")) return RedirectToAction("Index", "Employee");
            }
            return View();
        }

        //
        // GET: /Account/Details/5

        [HttpPost]
        public ActionResult LogOn(Account account, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (_accountProvider.Login(account))
                {
                    var emp = _eap.GetEmployeeByCode(account.Username);
                    EmpAccount = emp;
                    //AuthenticateRedirection(emp);
                    var roles = _eap.GetRolesOfEmp(emp);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                      && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        //Redirect to default page
                        if (roles[0].Contains("FV")) return RedirectToAction("FVCustomers", "CusMgn");
                        if (roles[0].Contains("Reviewer")) return RedirectToAction("Allocation", "CusMgn");
                        if (roles[0].Contains("Admin")) return RedirectToAction("Index", "Employee");
                    }
                    return RedirectToAction("LogOn");
                }
                else
                {
                    return RedirectToAction("LogOn");
                }
            }
            else
            {
                return View(account);
            }

        }

        public ActionResult LogOut()
        {
            _accountProvider.LogOut();
            return RedirectToAction("Logon");
        }
    }
}
